import re
import sqlite3
import os
import logging
from django.http import HttpResponse
from django.conf import settings
import json
import logging
import sqlite3
import re
import os
import random
import datetime
from concurrent.futures import ThreadPoolExecutor,ProcessPoolExecutor
import threading
logging.basicConfig(level=logging.DEBUG,format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',datefmt='%a, %d %b %Y %H:%M:%S')

def display(request):

	if request.method == 'POST':
		try:	
			received_json_data=json.loads(request.body.decode().replace("'", "\""))
			logging.info("\n\n\n\t"+str(received_json_data)+"\n\n")
			pageNo=received_json_data['pageNo']
			pageNo=int(pageNo)
			
			erpName=received_json_data['erpName'].strip()
			erpName_val=received_json_data['erpName'].strip()
			user_input=erpName_val			
			user_inputNum=6
			inquiryType='erpName_val'
			allResultStrShow=inquiryMain(user_input,inquiryType,pageNo)		
			return HttpResponse(json.dumps(allResultStrShow,ensure_ascii=False),content_type="application/json;charset=utf-8")
		except:
			logging.info('\n\n\n\t输入格式有误\n\n')
			resultError={'result':'请检查格式','code':1}
			return HttpResponse(json.dumps(resultError,ensure_ascii=False),content_type="application/json;charset=utf-8")
	else:
		pass
#通过任务负责人
def inquiryMain(user_input,inquiryType,pageNo):
	start=datetime.datetime.now()
	user_input=user_input
	
	inquiryType=inquiryType
	db_path = os.path.normpath('/export/datamarket/OozieProperties/oozie_project/db.sqlite3') 
	db = sqlite3.connect(db_path) 
	
	# 通过cursor创建游标
	cursor = db.cursor()
	cursorCountAll=db.cursor()


		
	#符合有求的总条数

	sql_countAll="select count(*) from oozie_configuration where "+inquiryType+" like '{}'".format(user_input)
	cursor.execute(sql_countAll)
	dataCountAll=cursor.fetchall()
	dataCountAll=dataCountAll[0][0]
	
	#总页数
	if dataCountAll%10==0:
		pageNumAll=int(dataCountAll/10)
	else:
		pageNumAll=int(dataCountAll/10)+1
	
	if pageNo<=pageNumAll and pageNo>=1:
		#每页展示10条信息
		if pageNo==1:
			sql_cmd = "select * from oozie_configuration where "+inquiryType+" like '{}' limit 10".format(user_input)
			sql_pageSize="select count(*) from(select * from oozie_configuration where "+inquiryType+" like '{}' limit 10)".format(user_input)
		else:
			sql_cmd = "select * from oozie_configuration where "+inquiryType+" like '{}'".format(user_input)+" limit "+str(10*(pageNo-1))+",10"
			sql_pageSize="select count(*) from(select * from oozie_configuration where "+inquiryType+" like '{}'".format(user_input)+" limit "+str(10*(pageNo-1))+",10)"
		cursor.execute(sql_cmd)
		dataShow = cursor.fetchall()
		cursor.execute(sql_pageSize)
		pageSize=cursor.fetchall()
		pageSize=pageSize[0][0]
		allResult=[]
		threads=[]
		url_list = []
		for i in range(pageSize):
			t = threading.Thread(target=inquiryMainOozie,args=(dataShow,i,start,allResult))
			threads.append(t)
		for t in threads:
			t.start()
		for t in threads:
			t.join()
		cursor.close()
		db.commit()
		db.close()
		logging.info(datetime.datetime.now()-start)
		logging.info({'data':allResult,'code':0,'totalCount':dataCountAll,'totalPageNum':pageNumAll,'currentPage':pageNo,'pageSize':pageSize})
		return {'data':allResult,'code':0,'totalCount':dataCountAll,'totalPageNum':pageNumAll,'currentPage':pageNo,'pageSize':pageSize}
	else:
		pageNoResult={'result':'输入页数'+str(pageNo)+' not in (1,'+str(pageNumAll)+')','code':3}
		logging.info(pageNoResult)
		return {'result':'输入页数'+str(pageNo)+' not in (1,'+str(pageNumAll)+')','code':3}
def inquiryMainOozie(dataShow,i,start,allResult):
			#dataShow[i]=dataShow
			i=i
			
			start=start
			allResult=allResult
			#通过任务名称查找相关信息
			randomNum=os.popen('echo -n `date +%s%N`').read()
			jobIDinfoFile='jobIDinfoDisplay'+str(randomNum)+str(random.uniform(1, 24))
			jobidFile='jobidDisplay'+str(randomNum)+str(random.uniform(1, 24))
			os.system("oozie jobs -localtime -filter 'name={}' -len 1 > {}".format(dataShow[i][1],jobIDinfoFile))
		
			######os.system("cat jobIDinfo| awk -F ' ' '{print$1}' > jobid")
			######os.system("sed -i '1d' jobid ")
			######os.system("sed -i '1d' jobid ")
			######os.system("sed -i '2d' jobid ")
			######jobid=os.popen("cat jobid").read().strip()
			jobid=jobid=dataShow[i][0]
			#执行时间
			time_val=dataShow[i][2]
			mission_discription=dataShow[i][5]
			#任务名称
			os.system("cat {}".format(jobIDinfoFile)+"| awk -F ' ' '{print$2}' > "+jobidFile)
			os.system("sed -i '1d' {}".format(jobIDinfoFile))
			#mission_val=os.popen("cat jobid").read().strip()
			mission_val=dataShow[i][1]
			#print(mission_val)
			os.system("cat {}".format(jobIDinfoFile)+"| awk -F ' ' '{print$3}' > "+jobidFile)
			os.system("sed -i '1d' {}".format(jobidFile))
			status=dataShow[i][6]
			shellName=dataShow[i][7]
			shellID=dataShow[i][9]
			if status=='禁用':
				status='禁用'
			else:
				status=os.popen("cat {}".format(jobidFile)).read().strip()
				if status=='SUCCEEDED':
					status='成功'
				elif status =='KILLED' or status=='FAILED':
					status='失败'
				elif status=='RUNNING':
					status='执行中'
				elif status=='SUSPENDED':
					status='队列中'
				else:
					status=os.popen("cat {}".format(jobidFile)).read().strip()
			#print(status)
			#os.system("cat jobIDinfo| awk -F 'CST' '{print$1}' | awk -F '-' '{print$6}'> jobid")
			os.system("cat {}".format(jobIDinfoFile)+"| awk -F 'CST' '{print$1}' > "+jobidFile)
			os.system("sed -i '1d' {}".format(jobidFile))
			try:
				startTime=re.findall(r"oozie-root-W(.*)\s+",os.popen("cat {}".format(jobidFile)).read().strip())[0]
				startTime=re.findall(r"-(.*)\s+",startTime)[0].strip()
			except:
				startTime=''
			os.system("cat {}".format(jobIDinfoFile)+"| awk -F 'CST' '{print$2}' > "+jobidFile)
			try:
				endTime=os.popen("cat {}".format(jobidFile)).read().strip()
			except:
				endTime=''
			erpName=dataShow[i][3]
			#获取任务创建时间和下一次执行时间

			os.system("oozie jobs -localtime -filter 'name={}' -len 1 -jobtype coordinator > {}".format(mission_val,jobIDinfoFile))
			os.system("sed -i '1d' {}".format(jobIDinfoFile))
			os.system("sed -i '1d' {}".format(jobIDinfoFile))
			os.system("sed -i '2d' {}".format(jobIDinfoFile))
			try:
				createTime=re.findall(r"CRON(.*?)CST",os.popen("cat {}".format(jobIDinfoFile)).read().strip())[0].strip()
			except:
				createTime=''
			os.system("cat {}".format(jobIDinfoFile)+"| awk -F 'CST' '{print$2}' > "+jobidFile)
			try:
				nextExecTime=os.popen("cat {}".format(jobidFile)).read().strip()
			except:
				nextExecTime=''
			os.remove('{}'.format(jobIDinfoFile))
			os.remove('{}'.format(jobidFile))
			#要展示的信息
			allResultSingle={'jobid':jobid,'mission_val':mission_val,'time_val':time_val,'mission_status':status,'startTime':startTime,'endTime':endTime,'erpName':erpName,'createTime':createTime,'nextExecTime':nextExecTime,'mission_discription':mission_discription,'mission_type':'','shellName':shellName,'shellID':shellID,'auditing_status':'','monitor':'','execMethod':''}
			allResult.append(allResultSingle)

